<template>
	<view class="main">
		<!-- 基本信息start -->
		<view class="base_info">
			<view class="title"> 基本信息 </view>
			<view class="info_item_box d-flex a-center j-sb">
				<view class="info_item_title d-flex a-center">
					<text class="require_icon"> * </text>
					安装厂家
				</view>
				<view class="d-flex a-center">
					<u-input border="none" v-model.trim="form.companyName" placeholder="请输入安装厂家"></u-input>
				</view>
			</view>
			<view class="info_item_box d-flex a-center j-sb" @click="selectTime">
				<view class="info_item_title d-flex a-center">
					<text class="require_icon"> * </text>
					安装日期
				</view>
				<view class="d-flex a-center">
					<view :class="[
              'content_text',
              'text-nowrap',
              form.installDate ? 'act' : '',
            ]">
						{{
              form.installDate
                ? $format(form.installDate, "yyyy-MM-dd")
                : "请选择"
            }}
					</view>
					<image src="https://public-test-shengtong.oss-cn-zhangjiakou.aliyuncs.com/yixiao_h5/my/enter_icon.png"
						class="edit_icon"></image>
				</view>
			</view>
			<view class="info_item_box d-flex a-start j-sb" style="height: auto; padding: 26rpx 0">
				<view class="info_item_title d-flex a-center">
					<text class="require_icon"> * </text>
					安装地址
				</view>
				<view class="d-flex a-center">
					<u-textarea border="none" v-model.trim="form.address" placeholder="请输入安装地址">
					</u-textarea>
				</view>
			</view>
		</view>
		<!-- 基本信息end -->
		<!-- 安装信息start -->
		<view class="base_info">
			<view class="title"> 安装信息 </view>
			<scroll-view scroll-x="true" class="goods_list" v-if="form.cabinets && form.cabinets.length">
				<view class="goods">
					<view class="goods_item d-flex">
						<view class="item_title"> 名称 </view>
						<view class="item_content text-nowrap" v-for="(item, index) in form.cabinets" :key="index">
							<view class="goods_name text-nowrap d-flex a-center">
								<view class="item_name text-nowrap" @click="editCabinet(index)">
									{{ item.name }}
									<image class="edit_blue"
										src="https://public-test-shengtong.oss-cn-zhangjiakou.aliyuncs.com/yixiao_h5/student/edit_blue.png">
									</image>
								</view>
								<image @click="delCabinet(index)"
									src="https://public-test-shengtong.oss-cn-zhangjiakou.aliyuncs.com/yixiao_h5/student/red_delet.png"
									class="delete_icon"></image>
							</view>
						</view>
					</view>
					<view class="goods_item d-flex">
						<view class="item_title"> 单价 </view>
						<view class="item_content text-nowrap" v-for="(item, index) in form.cabinets" :key="index">
							{{
                item.unitPrice ? `${keepThreeNum(Number(item.unitPrice))}` : ""
              }}
							<text class="unit">元/m²</text>
						</view>
					</view>
					<view class="goods_item d-flex">
						<view class="item_title"> 尺寸 </view>
						<view class="item_content text-nowrap" v-for="(item, index) in form.cabinets" :key="index">
							{{
                item.area
                  ? `${item.num1}×${item.num2}=${keepThreeNum(
                      Number(item.area)
                    )}`
                  : ""
              }}
							<text class="unit">m²</text>
						</view>
					</view>
					<view class="goods_item d-flex">
						<view class="item_title border_btm"> 总价 </view>
						<view class="item_content text-nowrap border_btm" v-for="(item, index) in form.cabinets" :key="index">
							{{
                item.unitPrice && item.area
                  ? `${item.unitPrice}×${item.area}=${keepThreeNum(
                      Number(item.totalPrice)
                    )}`
                  : ""
              }}
							<text class="unit">元</text>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="blank_data" v-else>
				<img src="https://public-test-shengtong.oss-cn-zhangjiakou.aliyuncs.com/yixiao_h5/newHome/blank_page.png"
					alt="" />
				<view class="tip_text"> 暂无信息，添加后查看 </view>
			</view>
		</view>
		<!-- 安装信息end -->
		<!-- 费用信息start -->
		<view class="base_info">
			<view class="title"> 费用信息 </view>
			<view class="info_item_box d-flex a-center j-sb">
				<view class="info_item_title d-flex a-center">
					<text class="require_icon opcity"> * </text>
					安装总价
					<text class="unit">(元)</text>
				</view>
				<view class="d-flex a-center">
					<view :class="[
              'content_text',
              'text-nowrap',
              form.installTotalPrice ? 'act' : '',
            ]">
						{{
              form.installTotalPrice ? form.installTotalPrice : "暂无安装总价"
            }}
					</view>
				</view>
			</view>
			<view class="info_item_box d-flex a-center j-sb">
				<view class="info_item_title d-flex a-center">
					<text class="require_icon opcity"> * </text>
					附加费用
					<text class="unit">(元)</text>
				</view>
				<view class="d-flex a-center">
					<u-input border="none" v-model.trim="form.additionalCost" placeholder="请输入"></u-input>
				</view>
			</view>
		</view>
		<!-- 费用信息end -->
		<!-- 备注start -->
		<view class="remark_box">
			<view class="title"> 备注 </view>
			<u-textarea height="156rpx" border="none" maxlength="-1" v-model="form.remark" placeholder="请输入"
				placeholderStyle="color: #BABABA"></u-textarea>
		</view>
		<!-- 备注end -->
		<view class="operation d-flex">
			<view @click="saveData" class="btn">保 存</view>
			<view @click="exportData" class="btn">生成报价单</view>
		</view>
		<view class="add_record_btn" @click="addCabinet"> </view>
		<!-- 选择日期start -->
		<u-datetime-picker :show="showDate" v-model="date" mode="date" :formatter="formatter" @confirm="confirmDate"
			@cancel="showDate = false" :closeOnClickOverlay="true" @close="showDate = false"></u-datetime-picker>
		<!-- 选择日期end -->
	</view>
</template>

<script>
	import QQMapWX from '../../qqmap/qqmap-wx-jssdk.min.js'
	export default {
		props: {},
		components: {},
		data() {
			return {
				form: {
					cabinets: [],
					additionalCost: null,
					installDate: null,
					address: null,
					installTotalPrice: 0,
				},
				date: Number(new Date()),
				showModal: false,
				content: '是否确认删除',
				dataId: '',
				showDate: false,
			}
		},
		watch: {},
		onShow() {
			this.onShowInit()
		},
		onLoad(option) {
			if (option.id) {
				this.dataId = option.id
				this.getItemData()
			}
			// #ifdef MP-WEIXIN
			wx.enableAlertBeforeUnload({
				message: '本次数据还未保留，确认返回吗？',
				success: function(res) {
					console.log('点击确认按钮了：', res)
				},
				fail: function(errMsg) {
					console.log('点击取消按钮了：', errMsg)
				},
			})
			// #endif
		},
		created() {},
		mounted() {
			console.log('123mounted', this.dataId)
			if (!this.dataId) {
				this.init()
			}
		},
		methods: {
			init() {
				let location = {}
				let that = this
				console.log(123)
				// 获取定位
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						console.log('授权')
						uni.getFuzzyLocation({
							type: 'gcj02',
							success(res) {
								console.log('gcj02', res)
								let qqmapsdk = new QQMapWX({ key: 'DWQBZ-464KQ-STA54-4AZCC-VHEHZ-DUBQ3' })

								qqmapsdk.reverseGeocoder({
									location: {
										latitude: res.latitude, //回调的纬度
										longitude: res.longitude //回调的经度
									},
									//回调成功显示位置的详细数据
									success: res2 => {
										console.log(res2, res2.result.address)
										that.form.address = res2.result.address
									},
									//回调失败  （调用成功之后这个可以不需要 ，回调失败会有报错信息方便调试）
									fail: function(fail) {
										console.log('fail', fail)
									},
									//成功失败都会执行
									complete: function(complete) {
										console.log(complete, 'complete')
									}
								})
							},
							fail(err) {
								console.log(err)
							}
						})
					}
				})

				// 设置时间
				this.form.installDate = new Date()
			},
			addCabinet() {
				uni.navigateTo({ url: '/pages/index/addCabinet' })
			},
			delCabinet(index) {
				this.form.cabinets.splice(index, 1)
				this.installCost()
			},
			editCabinet(index) {
				uni.setStorageSync(
					'cabinetInfo',
					JSON.stringify({ ...this.form.cabinets[index], index })
				)
				uni.navigateTo({ url: '/pages/index/addCabinet?modify=true' })
			},
			// 生成报价单 先保存数据 获取id后再跳转页面查看
			exportData() {
				if (this.dataId) {
					console.log(this.dataId, 'this.dataId')
					uni.redirectTo({ url: `/pages/index/quotation?id=${this.dataId}`, })
				} else {
					this.saveData(1)
				}
			},
			// 有值则代表是点击的生成报价单
			// 否则是点击的保存按钮
			saveData(value) {
				if (!this.form.companyName) {
					uni.showToast({
						title: '请输入安装厂家',
						icon: 'none',
					})
					return
				}
				if (!this.form.address) {
					uni.showToast({
						title: '请输入安装地址',
						icon: 'none',
					})
					return
				}
				if (!this.form.cabinets || !this.form.cabinets.length) {
					uni.showToast({
						title: '请添加安装信息',
						icon: 'none',
					})
				}
				// 修改
				this.form.totalArea = this.form.cabinets.reduce((total, item) => {
					return total + item.area
				}, 0)
				if (this.form._id) {
					this.$api.updateInstall({ ...this.form }).then(res => {
						if (res.code == 200) {
							uni.showToast({
								title: '修改成功',
								icon: 'none',
							})
							uni.switchTab({ url: '/pages/index/index' })
						} else {
							uni.showToast({
								title: res.msg || '修改失败',
								icon: 'none',
							})
						}
					})
				} else {
					// 添加
					this.$api.addInstall({ ...this.form }).then(res => {
						if (res.code == 200) {
							uni.showToast({
								title: '保存成功',
								icon: 'none',
							})
							if (value) {
								uni.redirectTo({ url: `/pages/index/quotation?id=${res.id}`, })
							} else {
								uni.switchTab({ url: '/pages/index/index' })
							}
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
							})
						}
					})
				}
			},
			getItemData() {
				this.$api
					.queryInstallItem({ id: this.dataId, })
					.then(res => {
						if (res.code == 200) {
							this.form = res.data
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
							})
						}
					})
			},
			onShowInit() {
				if (uni.getStorageSync('addInfo')) {
					let info = JSON.parse(uni.getStorageSync('addInfo'))
					if (info.unitPrice && info.area) {
						let sum = info.area * info.unitPrice
						info.totalPrice = this.keepThreeNum(sum)
					}
					// 有index值则是修改  否则是新增
					if (
						info.index !== undefined &&
						info.index !== null &&
						info.index !== ''
					) {
						this.form.cabinets.splice(info.index, 1, info)
					} else {
						this.form.cabinets.push(info)
					}
					uni.removeStorageSync('addInfo')
					this.installCost()
				}
			},
			// 计算安装总价
			installCost() {
				console.log(this.form.cabinets, 'this.form.cabinets')
				if (this.form.cabinets.length > 0) {
					this.form.installTotalPrice = this.form.cabinets.reduce(
						(prev, itme) => {
							return prev + (itme.totalPrice - 0)
						},
						0
					)
					console.log(this.form.installTotalPrice, 'this.form.installTotalPrice')
				} else {
					this.form.installTotalPrice = 0
				}
			},
			selectTime() {
				this.showDate = true
			},
			// 日期选择器确定按钮
			confirmDate(data) {
				this.form.installDate = data.value
				this.showDate = false
			},
			// 保留三位小数
			keepThreeNum(value) {
				let resValue = Math.round(value * 1000) / 1000
				return resValue
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
		},
	}
</script>

<style scoped lang='scss'>
	.unit {
		margin-left: 8rpx;
		font-size: 20rpx;
	}

	.blank_data {
		height: 300rpx;
		padding-top: 90rpx;
		text-align: center;
		box-sizing: border-box;

		&>img {
			width: 104rpx;
			height: 104rpx;
		}

		.tip_text {
			font-size: 24rpx;
			text-align: center;
			color: #bababa;
			line-height: 34rpx;
		}
	}

	.remark_box /deep/.u-textarea {
		padding: 8rpx 0 0 16rpx !important;
	}

	.remark_box /deep/textarea {
		font-size: 28rpx !important;
		line-height: 40rpx !important;
	}

	/deep/input {
		width: 400rpx;
		height: 40rpx !important;
		text-align: right !important;
		font-size: 28rpx !important;
		line-height: 40rpx !important;
		color: #222 !important;
		font-weight: 500;
	}

	/deep/u-textarea {
		width: 400rpx;
		text-align: right !important;
		font-size: 28rpx !important;
		line-height: 40rpx !important;
		color: #222 !important;
		font-weight: 500;
	}

	.title {
		margin-bottom: 32rpx;
		padding-left: 16rpx;
		font-size: 32rpx;
		font-weight: 550;
		text-align: left;
		color: #222222;
		line-height: 44rpx;
		box-sizing: border-box;
	}

	.edit_icon {
		width: 28rpx;
		height: 28rpx;
		margin-left: 8rpx;
		margin-right: 0;
	}

	.act {
		color: #222 !important;
	}

	.main {
		min-height: 100vh;
		padding-bottom: 200rpx;
		background-color: #f5f7fa;
	}

	.base_info {
		margin-bottom: 16rpx;
		padding: 32rpx 24rpx 32rpx 16rpx;
		box-sizing: border-box;
		background: #fff;

		.info_item_box {
			height: 88rpx;

			.info_item_title {
				font-size: 28rpx;
				color: #222;
				line-height: 36rpx;

				.require_icon {
					margin-right: 8rpx;
					font-size: 32rpx;
					font-weight: 550;
					text-align: left;
					color: #dc3545;
				}

				.opcity {
					opacity: 0;
				}
			}

			.content_text {
				color: #c0c4cc;
				font-size: 28rpx;
			}

			/deep/.u-textarea {
				width: 400rpx;
				padding: 0 !important;
				text-align: right !important;
				font-size: 28rpx !important;
				line-height: 40rpx !important;
				color: #222 !important;
				font-weight: 500;
			}

			/deep/.input-placeholder {
				font-size: 28rpx !important;
				color: #c0c4cc;
				font-weight: 400 !important;
			}
		}

		.goods_list {
			.goods {
				.goods_item {
					.item_title {
						flex-shrink: 0;
						width: 150rpx;
						height: 76rpx;
						padding-left: 14rpx;
						text-align: center;
						color: #999999;
						line-height: 76rpx;
						font-size: 24rpx;
						border: 2rpx solid #eef0f2;
						border-bottom: none;
						box-sizing: border-box;
					}

					.item_content {
						flex-shrink: 0;
						width: 500rpx;
						height: 76rpx;
						line-height: 76rpx;
						font-size: 28rpx;
						text-align: center;
						color: #222222;
						border: 2rpx solid #eef0f2;
						border-left: none;
						border-bottom: none;
						box-sizing: border-box;

						.goods_name {
							position: relative;
							width: 500rpx;
							margin: 0 auto;
							color: #3f7fff;

							.item_name {
								width: 450rpx;
							}

							.edit_blue {
								width: 24rpx;
								height: 24rpx;
								margin-left: 16rpx;
							}

							.delete_icon {
								width: 24rpx;
								height: 24rpx;
							}
						}
					}

					.border_btm {
						border-bottom: 2rpx solid #eef0f2;
					}
				}
			}
		}
	}

	.remark_box {
		padding: 32rpx;
		margin-bottom: 16rpx;
		background-color: #fff;
		box-sizing: border-box;
	}

	.add_record_btn {
		position: fixed;
		right: 32rpx;
		bottom: 208rpx;
		width: 128rpx;
		height: 128rpx;
		background: url("https://public-test-shengtong.oss-cn-zhangjiakou.aliyuncs.com/yixiao_h5/student/add_record.png") no-repeat;
		background-size: 100% 100%;
		z-index: 10;
	}

	.operation {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background: #fff;
		height: 180rpx;
		z-index: 9;

		.btn {
			flex: 1;
			height: 80rpx;
			color: #fff;
			line-height: 80rpx;
			background: #4087ff;
			border-radius: 40rpx;
			text-align: center;
			margin: 0rpx 24rpx;
			margin-top: 16rpx;
			font-size: 32rpx;
		}
	}
</style>